import { Controller } from "egg";
import { IndexCondition } from "../common";

export default class StandardController extends Controller {
  /**
   * 列表查询
   */
  public async index() {
    const { ctx } = this;
    const { pageSize, pageIndex, standard } = ctx.query;
    const _listCondition: IndexCondition = {
      select: "standard createdAt",
      find: {
        is_delete: false,
        ...(standard && { standard: { $regex: standard, $options: "i" } }),
      },
      ...(pageIndex && { pageIndex: parseInt(pageIndex) - 1 }),
      ...(pageSize && { pageSize: parseInt(pageSize) }),
    };
    const res = await ctx.service.standard.findList(_listCondition);
    ctx.helper.success({ ctx, res });
  }

  /**
   * 数据添加
   */
  public async create() {
    const { ctx, service } = this;
    const { standard } = ctx.request.body;
    const data = await service.standard.findByName(standard);
    if (data) {
      return ctx.helper.error({ ctx, errorType: "commonAlreadyExists" });
    }
    const res = await service.standard.add(ctx.request.body);
    ctx.helper.success({ ctx, res });
  }
}
